package cn.itlemon.security.main.handler;

import cn.hutool.json.JSONUtil;
import cn.itlemon.security.core.entity.common.ReturnMessage;
import cn.itlemon.security.core.entity.common.ReturnState;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证失败后的处理器
 *
 * @author jiangpingping
 * @date 2019/9/18 21:55
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();
        ReturnMessage<String> rm = new ReturnMessage<>(ReturnState.ERROR);
        rm.setErrorMessage(exception.getMessage());
        writer.write(JSONUtil.toJsonStr(rm));
    }
}
